#!/bin/bash

set -e
cd "$(dirname "$0")"/../..

# Clone poppler dir from main portage tree
rm -r app-text/poppler
cp -r "${PORTDIR:-/usr/portage}/app-text/poppler" app-text/

# Make adjustments to ebuilds
sed -i \
    -e '/^IUSE/N' \
    -e 's/^\(IUSE=.*\) qt4/\1 qt3 qt4/' \
    -e 's/-DWITH_Qt3=OFF/$(cmake-utils_use_with qt3)/' \
    -e 's/^\([ \t]*\)\(qt4? (\)/\1qt3? ( >=x11-libs\/qt-meta-3.3:3 )\n\1\2/' \
    -e 's/^\(inherit.*\)/\1 qt3/' \
    app-text/poppler/*.ebuild

# Drop all unmodified ebuilds, e.g. for older versions without qt4 USE flag
# For modified files, check number of changes
for i in app-text/poppler/*.ebuild; do
    cmp -s "$i" "${PORTDIR:-/usr/portage}/$i" && rm $i
    nchg="$(diff -U0 "${PORTDIR:-/usr/portage}/$i" "$i" | grep ^+ | wc -l)"
    if [[ $nchg -ne 5 ]]; then
        diff -U0 "${PORTDIR:-/usr/portage}/$i" "$i" | grep ^+
        echo "Unexpected number of changes in $i: $nchg changes" >&2
        exit 1
    fi
done

# Redigest and show difference
ebuild $(ls -1 app-text/poppler/*.ebuild | tail -n1) digest
Documentation/maintainers/generate_unmask

git add -A app-text/poppler Documentation/package.unmask/kde-3.5
git status
echo 'Run: git commit -m "[app-text/poppler] Update from main portage tree"'
